package dp.mobile.eden;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import dp.mobile.level.CutScene;
import dp.mobile.level.CutScene.MiniDialog;

public class CutSceneAct extends Activity {
	private static final String TAG = "Cut Scene Activity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cutscene);
		
		mLevelSource = getIntent().getExtras().getString("level");
		mCutScenes = CutScene.fromLevel(mLevelSource);
		
		if (mCutScenes == null) {
			onFinishCutScene();
		}
		
		//Log.d(TAG, "Jumlah cutscene = " + mCutScenes.size());
		
		mOkArrow = (ImageView)findViewById(R.id.ok);
        mOkArrow.setBackgroundResource(R.anim.ui_button);
		mOkAnimation = (AnimationDrawable) mOkArrow.getBackground();
		mOkArrow.setVisibility(View.INVISIBLE);
		
		mChar 		= new ImageView[4];
		mCharBitmap = new Bitmap[4];
		
		mChar[0] = (ImageView)findViewById(R.id.char0);
		mChar[1] = (ImageView)findViewById(R.id.char1);
		mChar[2] = (ImageView)findViewById(R.id.char2);
		mChar[3] = (ImageView)findViewById(R.id.char3);
		
		mBackground = (ImageView)findViewById(R.id.background);
        
    	TypewriterTextView tv = (TypewriterTextView)findViewById(R.id.typewritertext);   
    	tv.setParentActivity(this);
    	
    	System.gc();
	}
	
	@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            TypewriterTextView tv = (TypewriterTextView)findViewById(R.id.typewritertext);        
            
            if (tv.getRemainingTime() > 0) {
                tv.snapToEnd();
            } else {
            	MiniDialog dialog = mCutScenes.get(mCurrentCutScene).advanceDialog();
            	
            	if (dialog == null) {
            		++mCurrentCutScene;
            		if (mCurrentCutScene < mCutScenes.size()) {
            			mBackgroundBitmap.recycle();
            			mBackgroundBitmap = BitmapFactory.decodeFile(mCutScenes.get(mCurrentCutScene).getBackgroundResource());
            	    	mBackground.setImageBitmap(mBackgroundBitmap);
            	    	
            	    	if (mCutScenes.get(mCurrentCutScene).isSubSceneUpdated()) {
                			CutScene.SubCutScene subCutScene = mCutScenes.get(mCurrentCutScene).getCurrentScene();
                	    	for (int i = 0; i < 4; ++i) {
                	    		if (mCharBitmap[i] != null)
                	    			mCharBitmap[i].recycle();
                	    		if (subCutScene.getCharImageResource(i) != null) {
                	    			mCharBitmap[i] 	= BitmapFactory.decodeFile(subCutScene.getCharImageResource(i));
                	    			mChar[i].setImageBitmap(mCharBitmap[i]);
                	    		}
                	    	}
                		}
            	    	
            			dialog = mCutScenes.get(mCurrentCutScene).getCurrentDialog();
            			if (dialog != null)
            				showPage(dialog);
            			else {
            				onFinishCutScene();
            			}
            		} else {
            			onFinishCutScene();
            		}
            	} else {
            		if (mCutScenes.get(mCurrentCutScene).isSubSceneUpdated()) {
            			CutScene.SubCutScene subCutScene = mCutScenes.get(mCurrentCutScene).getCurrentScene();
            	    	for (int i = 0; i < 4; ++i) {
            	    		if (mCharBitmap[i] != null)
            	    			mCharBitmap[i].recycle();
            	    		if (subCutScene.getCharImageResource(i) != null) {
            	    			mCharBitmap[i] 	= BitmapFactory.decodeFile(subCutScene.getCharImageResource(i));
            	    			mChar[i].setImageBitmap(mCharBitmap[i]);
            	    		}
            	    	}
            		}
            		
            		showPage(dialog);
            	}
            }
        }
        // Sleep so that the main thread doesn't get flooded with UI events.
        try {
            Thread.sleep(32);
        } catch (InterruptedException e) {
            // No big deal if this sleep is interrupted.
        }
        return true;
    }
	
	protected void onFinishCutScene() {
		finish();
		Intent intent = new Intent(CutSceneAct.this.getApplicationContext(), CampaignAct.class);
		intent.putExtra("level", mLevelSource);
		startActivity(intent);
	}
    
    protected void showPage(MiniDialog page) {
        TypewriterTextView tv = (TypewriterTextView)findViewById(R.id.typewritertext);        
        tv.setTypewriterText(page.getText());
        
		mOkArrow.setVisibility(View.INVISIBLE);
		mOkAnimation.start();

		tv.setOkArrow(mOkArrow);
        
        TextView title = (TextView)findViewById(R.id.speakername);
        if (page.getSpeaker() != null) {
            title.setText(page.getSpeaker());
            title.setVisibility(View.VISIBLE);
        } else {
        	title.setVisibility(View.INVISIBLE);
        }
    }
    
    public void processText() {
		//TextView textView = (TextView)findViewById(R.id.typewritertext);
		//formatPages(mCutScenes.get(mCurrentCutScene).getCurrentDialog(), textView);
    	
    	CutScene cutScene = mCutScenes.get(mCurrentCutScene);

    	mBackgroundBitmap = BitmapFactory.decodeFile(cutScene.getBackgroundResource());
    	mBackground.setImageBitmap(mBackgroundBitmap);
    	
    	CutScene.SubCutScene subCutScene = cutScene.getCurrentScene();
    	for (int i = 0; i < 4; ++i) {
    		if (subCutScene.getCharImageResource(i) != null) {
    			mCharBitmap[i] 	= BitmapFactory.decodeFile(subCutScene.getCharImageResource(i));
    			mChar[i].setImageBitmap(mCharBitmap[i]);
    		}
    	}
    	
    	showPage(cutScene.getCurrentDialog());
        mCurrentCutScene = 0;
    }
	
	
	public static class TypewriterTextView extends TextView {
        
        
        public TypewriterTextView(Context context) {
            super(context);
        }
        
        public TypewriterTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        
        public TypewriterTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
        
        public void setParentActivity(CutSceneAct parent) {
        	mParentActivity = parent;
        }
        
        public void setTypewriterText(CharSequence text) {
            mText = text;
            mCurrentCharacter = 0;
            mLastTime = 0;
            postInvalidate();
        }
        
        public long getRemainingTime() {
            return (mText.length() - mCurrentCharacter) * TEXT_CHARACTER_DELAY_MS;
        }
        
        public void snapToEnd() {
            mCurrentCharacter = mText.length() - 1; 
        }
        
        public void setOkArrow(View arrow) {
        	mOkArrow = arrow;
        }
        
        
		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			// We need to wait until layout has occurred before we can setup the
			// text page.  Ugh.  Bidirectional dependency!  
			if (mParentActivity != null) {
				mParentActivity.processText();
			}
			super.onSizeChanged(w, h, oldw, oldh);
		}

		@Override
        public void onDraw(Canvas canvas) {
            final long time = SystemClock.uptimeMillis();
            final long delta = time - mLastTime;
            if (delta > TEXT_CHARACTER_DELAY_MS) {
                if (mText != null) {
                    if (mCurrentCharacter <= mText.length()) {
                        CharSequence subtext = mText.subSequence(0, mCurrentCharacter);
                        setText(subtext, TextView.BufferType.SPANNABLE);
                        mCurrentCharacter++;
                        postInvalidateDelayed(TEXT_CHARACTER_DELAY_MS);
                    } else {
                    	if (mOkArrow != null) {
                    		mOkArrow.setVisibility(View.VISIBLE);
                    	}
                    }
                }
            }
            super.onDraw(canvas);
        }
		
		private int mCurrentCharacter;
        private long mLastTime;
        private CharSequence mText;
        private View mOkArrow;
        private CutSceneAct mParentActivity;  // This really sucks.
    }

	private String mLevelSource;
	private int mCurrentCutScene;
	private ArrayList<CutScene> mCutScenes;
    
	private Bitmap mBackgroundBitmap;
	private Bitmap[] mCharBitmap;
	
	private ImageView mBackground;
	private ImageView[] mChar;
	
    private ImageView mOkArrow;
    private AnimationDrawable mOkAnimation;
    
	private final static float TEXT_CHARACTER_DELAY = 0.1f;
    private final static int TEXT_CHARACTER_DELAY_MS = (int)(TEXT_CHARACTER_DELAY * 1000);
}
